angular.module('app.knob', []).directive('knob', ['$timeout', function($timeout) {
    'use strict';

    return {
        restrict: 'EA',
        template: 	'<div style="text-align: center;">' +
        '<input value="{{ value }}"/>' +
        '<div class="text">' +
        '<div style="padding: 0px;">' +
        '<span style="font-size: {{options.valueSize}}; color:{{options.valueColor}}; font-weight: {{options.valueFontWeight}}">{{value}}</span>' +
        '<span style="font-size: {{options.unitSize}}; color: {{options.valueColor}}">{{options.unit}}</span>' +
        '</div>' +
        '<span ng-if="options.text" style="font-size: {{options.textSize}}; color:{{options.textColor}}">{{options.text}}</span>' +
        '</div>' +
        '</div>',
        replace: true,
        scope: {
            value: '=', 
            options: '='
        },
        link: function(scope, element, attr) {
            $(element).css({
                "position": "relative"
            });

            var text = $(element).find('.text');
            text.css({
                "position": "absolute",
                "top": "50%",
                "left": "0",
                "transform": "translateY(-50%)",
                "-webkit-transform": "translateY(-50%)",
                "text-align": "center",
                "width": "100%",
                "z-index": "1",
                "line-height": "1"
            });

            var _options = scope.options || {};
            _options.displayInput = false;
            _options.width = _options.height = _options.size || 200;
            var _value;
            _options.release = function(newValue) {
                $timeout(function() {
                    scope.value = newValue;
                    _value = newValue;
                });
            };

            var i = $(element).find("input");
            scope.$watch('value', function(newValue, oldValue) {
                if (newValue != oldValue && newValue != _value) {
                    i.val(newValue).trigger('change');
                }
            });

            scope.$watch('options.fgColor', function(newValue, oldValue) {
                if (newValue != oldValue) {
                    i.trigger('configure', {
                        fgColor: newValue
                    });
                }
            });

            i.val(scope.value).knob(_options);
        }
    };
}]);
